package com.tianbao54.concurrent.exchanger;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExchangerTest {

    public static void main(String[] args) {

        Exchanger<Product> exchanger = new Exchanger<>();
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(new Job(exchanger,new Product()));
        service.submit(new Job(exchanger,new Product()));

        service.shutdown();
    }

    static class Job implements Runnable {

        private final Exchanger<Product> exchanger;
        private final Product product;

        Job (Exchanger<Product> exchanger,Product product) {
            this.exchanger = exchanger;
            this.product = product;
        }

        @Override
        public void run() {
            System.out.println("线程：" + Thread.currentThread().getName() + " 已经准备好交换数据【" + product + "】");
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                Product productx = exchanger.exchange(product);
                System.out.println("线程：" + Thread.currentThread().getName() + " 已经交换数据完成【" + productx + "】");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Product {

        private String id;

        Product () {
            this.id = UUID.randomUUID().toString();
        }

        @Override
        public String toString() {
            return "id = " + id;
        }
    }

}
